package com.feature50.makeover.chart;

import com.feature50.makeover.utils.FontResolver;
import com.feature50.makeover.utils.Platform;

import javax.swing.*;
import java.awt.*;

public class BarChartLabel extends JComponent {
    private BarChartBars bars;

    private float built = 0f;

    private float max = 100;
    private String suffix = "%";

    public BarChartLabel(BarChartBars barChart) {
        this.bars = barChart;
        init();
    }

    private void init() {
        setFont(FontResolver.getFont(new FontResolver.FontInfo("LucidaGrandeBold", 8, true, true)));
        setBorder(BorderFactory.createEmptyBorder(4, 0, 4, 0));
    }

    public float getBuilt() {
        return built;
    }

    public void setBuilt(float built) {
        this.built = built;
    }

    public float getMax() {
        return max;
    }

    public void setMax(float max) {
        this.max = max;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public Dimension getMinimumSize() {
        return getPreferredSize();
    }

    public Dimension getPreferredSize() {
        int height = getInsets().top + getInsets().bottom;
        Graphics2D g2d = (Graphics2D) getGraphics().create();
        g2d.setFont(getFont());
        height += g2d.getFontMetrics().getAscent();
        g2d.dispose();
        return new Dimension(1, height);
    }

    public Dimension getMaximumSize() {
        return getPreferredSize();
    }

    protected void paintComponent(Graphics g) {
        if (built == 0) return;

        Graphics2D g2d = (Graphics2D) g.create();

        int x = bars.getValueX();
        int y = getInsets().top;
        int barWidth = bars.getTotalBarWidth();
        int increment = barWidth / bars.getSteps();
        int percentage = (int) (max / bars.getSteps());

        int ascent = g2d.getFontMetrics().getAscent();

        g2d.setColor(new Color(1f, 1f, 1f, built));
        Platform.setAntialiasing(g2d, getFont());
        for (int i = 0; i < bars.getSteps(); i++) {
            String s = String.valueOf(((int) max - (percentage * i)));
            s += suffix;
            String sn = "-" + s;

            int width, tx;

            if (bars.getValueAxisPosition() == BarChartBars.ValueAxisPosition.Center) {
                width = (int) g2d.getFontMetrics().getStringBounds(sn, g2d).getWidth();
                tx = (x + (increment * i)) - (width / 2);
                g2d.drawString(sn, tx, y + ascent);
            }

            width = (int) g2d.getFontMetrics().getStringBounds(s, g2d).getWidth();
            tx = x + bars.getValueWidth() - (increment * i) - (width / 2);
            g2d.drawString(s, tx, y + ascent);
        }

        g2d.dispose();
    }
}
